const models = require('./../../db/mysqldb/index')
const { SuccessModel, ErrorModel } = require('./../../utils/index')
const moment = require('moment')
const logger = require('./../../utils/logger')
class AdminSystemLog {
  /**
   * 创建系统日志
   * @param {String} uid 
   * @param {Number} type 
   * @param {String} content 
   */
  static async createAdminSystemLog (req, res) {
    const { uid, type = 1, content } = req.body
    logger.info('createAdminSystemLog', 'req.body', req.body)
    return models.system_log.create({
      uid,
      type,
      content,
    })
  }

  /**
   * 获取后台操作日志列表
   * @param {String} page 
   * @param {String} limit 
   */
  static async getAdminSystemLogList (req, res) {
    const { page = 1, limit = 10 } = req.query
    logger.info('getAdminSystemLogList', 'req.query', req.query)
    try {
      let { count, rows } = await models.system_log.findAndCountAll({
        where: '',
        offset: (Number(page) - 1) * Number(limit),
        limit: Number(limit)
      })
      logger.info('getAdminSystemLogList', 'count', count)
      logger.info('getAdminSystemLogList', 'rows', rows)

      for (const key in rows) {
        if (rows.hasOwnProperty(key)) {
          rows.create_dt = await moment(rows[i].create_date).format('YYYY-MM_DD H:m:s').toLocaleString()
          rows.admin_user = await models.admin_user.findOne({
            where: {
              uid: rows[i].uid
            },
            attributes: ['uid', 'nickname']
          })
        }
      }
      logger.info('getAdminSystemLogList', 'rows', rows)
      res.json(new SuccessModel({ count, rows, page, limit }))
    } catch (error) {
      logger.info('getAdminSystemLogList', 'error', error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * 删除日志
   * @param {*} id 
   */
  static async deleteAdminSystemLog (req, res) {
    const { id } = req.body
    logger.info('deleteAdminSystemLog', 'req.body', id)
    try {
      const deleteId = await models.system_log.destroy({ where: { id } })
      logger.info('deleteAdminSystemLog', 'deleteId', deleteId)
      res.json(new SuccessModel([], '删除成功'))
    } catch (error) {
      logger.info('deleteAdminSystemLog', 'error', error)
      res.json(new ErrorModel([], error.message))
    }
  }
}
module.exports = {
  AdminSystemLog
}